const db = require("../db");

// 创建博客
const createPost = async (
  title,
  content,
  summary,
  cover_image,
  category_id,
  status,
  userId
) => {
  if (!title || !content || !userId || !status) {
    throw new Error("缺少必要参数");
  }
  // 如果有created_at就只更新updated_at

  const sql = `
    INSERT INTO blogs (title, content, summary, cover_image, category_id, status, user_id, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
  `;
  const [results] = await db.query(sql, [
    title,
    content,
    summary,
    cover_image,
    category_id,
    status,
    userId,
  ]);
  return results;
};

// 列表
const getBlogList = async (pageNum, pageSize) => {
  const offset = (pageNum - 1) * pageSize;
  const limit = pageSize;
  const sql = `
    SELECT 
    b.id,
    b.title,
    b.content,
    b.summary,
    b.cover_image,
    b.category_id,
    b.status,
    b.created_at,
    b.views,
    b.likes,
    b.updated_at,
    u.username AS author_name,
    u.avatar AS author_avatar
    FROM blogs AS b
    LEFT JOIN users AS u ON b.user_id = u.id
    ORDER BY b.created_at DESC
    LIMIT ${offset},${limit} 
  `;
  const [results] = await db.query(sql, [(pageNum - 1) * pageSize, pageSize]);
  return results;
};

// 点赞和取消点赞
const likeBlog = async (blogId, status) => {
  if (!blogId || !status) {
    throw new Error("参数错误");
  }
  // 通过status判断likes+1还是likes-1
  const sql = `
    UPDATE blogs SET likes = likes ${status === 10 ? "+" : "-"} 1 WHERE id = ?
  `;
  await db.query(sql, [blogId]);
  return true;
};

module.exports = {
  createPost,
  getBlogList,
  likeBlog,
};
